import '../../pages/App.css';
import './Home.css'
import ClearSvg from '../../assets/clear.svg';
import HistorySvg from '../../assets/history.svg';
import Loading from '../../assets/loading.svg'
import ShuruIcon from '../../assets/shuru.svg'
import { useState, useRef,useEffect } from 'react'
import { IconSearch } from '@arco-design/web-react/icon';
import { Message, Modal, Input   } from '@arco-design/web-react';
import {
    useRecoilValue,
    useRecoilState
} from 'recoil';
import { getChats, deleteChat } from '../../api/all'
import axios from 'axios';
import copy from 'copy-to-clipboard';

import { currentAiChatState, robotListState, chatList,settingInfoState } from './store'
import {marked} from 'marked'

let layerMap = {
    2:2,3:3,4:2,6:3,8:2,9:3
}
axios.defaults.headers.common['token'] = window.localStorage.getItem('token') || window.sessionStorage.getItem('token');;
axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

function All() {
    const [controller, setController] = useState(new AbortController())
    const robotList = useRecoilValue(robotListState);
    const setting = useRecoilValue(settingInfoState);
    const [layerCount, setLayerCount] = useState(2);
    const [list, setList] = useState([])
    const [dialog, setDialog] = useRecoilState(chatList);
    const dialogRef = useRef();
    const [sendState,setSendState] = useState(true)
    const [visibleHisory, setVisibleHisory] = useState(false)
    const [history, setHistory] = useState([])
    const [historyGroup,setHistoryGroup] = useState({})
    const [currentChat,setCurrentChat] = useState({})
    const [visibleTips, setVisibleTips] = useState(false)

    useEffect(() => {
        if(setting){
            let together_ids = setting.together_ids && setting.together_ids.split(',')
            let together = setting.together
            if(together < together_ids.length){
                together_ids = together_ids.slice(0,together)
            }
            let all = robotList.filter((item)=>{
               return together_ids.includes(item.id+'')
            })

            setLayerCount(all.length)
            setList(all)
            setCurrentChat(all[0])
        }
    }, [setting,robotList]);

    const copyText = (text) => {
        copy(text);
        Message.success('复制成功')
    }

    const copyHtml = ((text) => {
        return <svg stroke="currentColor" onClick={()=>{
            copyText(text)
        }} fill="currentColor" strokeWidth="0" viewBox="0 0 512 512" className="self-top cursor-pointer invisible group-hover:visible mt-[12px] text-primary-text" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><rect width="336" height="336" x="128" y="128" fill="none" strokeLinejoin="round" strokeWidth="32" rx="57" ry="57"></rect><path fill="none" strokeLinecap="round" strokeLinejoin="round" strokeWidth="32" d="M383.5 128l.5-24a56.16 56.16 0 00-56-56H112a64.19 64.19 0 00-64 64v216a56.16 56.16 0 0056 56h24"></path></svg>
    })

    const loading = ((item) => {
        return (
            <div key={item.date} className="group flex gap-3 w-full flex-row mt-2">
                <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                    <div className="px-4 py-2 w-full answer">
                        <span className="leading-tight" style={{ display: "inherit" }}>
                            {/* <Spin dot /> 我在思考中... */}
                            <img className='loading_xzy' src={Loading} alt='' />我在思考中...
                        </span>
                    </div>
                </div>
            </div>
        )
    })

    const sendMsg = () => {
        let together_ids = setting.together_ids && setting.together_ids.split(',')
        setSendState(false)
        let ms = document.getElementById('myTextarea').value
        let msgObj = {
            role: 0,
            date: Date.now()+'',
            msg: ms
        }

        let chatlist = JSON.parse(JSON.stringify(dialogRef.current))

        list.map((obj)=>{
            let currentAi = JSON.parse(JSON.stringify(obj)) 
            let id = currentAi.id
            let log = chatlist[id]?.log || []
            log.push({ ...msgObj })
                log.push({
                    role: 2,
                    date: Date.now()+'',
                    msg: '......'
                })
            currentAi.log = log
            chatlist[id] = currentAi
        })

        setDialog(chatlist)
        document.getElementById('myTextarea').value = ''

        let allAjax = []
        // eslint-disable-next-line array-callback-return
        together_ids.map((id) => {
            allAjax.push(ajax(ms,id))
        })
        Promise.all(allAjax)
        .then(result => {
            console.log(result)

            let chatlist = JSON.parse(JSON.stringify(dialogRef.current))

            list.map((obj)=>{
                let currentAi = JSON.parse(JSON.stringify(obj)) 
                let id = currentAi.id
                let resultOne = result.filter((item)=>{return item.id == id})[0]
                let msg = resultOne.data
                let log = chatlist[id]?.log || []
                log.pop()
                log.push({ ...msg })
                currentAi.log = log
                chatlist[id] = currentAi
            })

            setDialog(chatlist)
            setSendState(true)
        })
        .catch(e => console.log(e));
    }

    const ajax = (ms,id) => {
        return new Promise((resolve, reject) => {
            axios.post('/chat/chatalls/chat',{
            // axios.post('http://47.92.247.100:7000/chatalls/chat', {
                content:ms,robot_id:Number(id),
            },{signal: controller.signal}).then(function(response) {
                let result = typeof (response.data?.result) === "string" ? response.data?.result : JSON.stringify(response.data?.result)
                resolve({id:id,data:{
                    role: 1,
                    date: Date.now()+'',
                    msg: response.data.code === 0 ? result : response.data?.message
                }});
             }).catch(()=>{
                return Promise.resolve({id:id,data:{
                    role: 1,
                    date: Date.now()+'',
                    msg: '服务器错误'
                }})
             });
        })
    }

    const cancelSend = () => {
        setSendState(true)
        controller.abort()
        setController(new AbortController())
        pushMsg({
            role: 1,
            date: Date.now()+'',
            msg: 'Cancelled'
        })
    }

    const pushMsg = (msg) => {
        let chatlist = JSON.parse(JSON.stringify(dialogRef.current))

        list.map((obj)=>{
            let currentAi = JSON.parse(JSON.stringify(obj)) 
            let id = currentAi.id
            let log = chatlist[id]?.log || []
            log.pop()
            log.push({ ...msg })
            currentAi.log = log
            chatlist[id] = currentAi
        })

        setDialog(chatlist)
    }

    useEffect(() => {
        dialogRef.current = dialog;
        list.length>0 &&  list.map((item)=>{
            let $div = document.getElementById('scrollDiv'+item.id);
            if($div){
                $div.scrollTop = $div.scrollHeight+200;
            }
        })
    }, [dialog]);

    useEffect(() => {
        bindEnter()
    }, [])

    const bindEnter = (e) => {
        if (e && e.keyCode === 13 && e.shiftKey) {

        } else if (e && e.keyCode === 13) {
            // 阻止原生的换行事件
            e.preventDefault();
            // TODO: 发消息
            sendMsg()
        }
    }

    const clearHistoryLocal = (id) => {
        let lo = JSON.parse(JSON.stringify(dialog))
        lo[id].log = []
        setDialog(lo)
    }
    const clearHistory = () => {
        deleteChat({ id: currentChat.id }).then((res) => {
            if (res.code === 0) {
                Message.success('清除成功')
                clearHistoryLocal(currentChat.id)
            }
        })
    }

    const checkHistory = (currentChat) => {
        setCurrentChat(currentChat)
        setVisibleHisory(true)
        getChats({
            robot_id: currentChat.id,
            page_num: 1,
            user_id: 74,
            page_size: 10000
        }).then((res) => {
            if (res.code === 0) {
                let hisChats = JSON.parse(JSON.stringify(history))
                res.result.list.forEach((item) => {
                    let date = item.created_at.split('T')[0] + ' ' + item.created_at.split('T')[1].slice(0,5)
                    let ask = {
                        date,
                        role: 0,
                        msg: item.question
                    }
                    let answer = {
                        date,
                        role: 1,
                        msg: item.answer
                    }
                    hisChats.push(ask, answer)
                })
                setHistory(hisChats)
                let a = groupedByDate(hisChats,'date')
                setHistoryGroup(a)
            }
        })
    }

    // 使用reduce进行分组
    const groupedByDate = (array,key) => {
        return array.reduce((acc, currentObj) => {
            // 将日期转换为键（如果需要的话，这里假设已经是格式化的日期字符串）
            let dateKey = currentObj[key].split('T')[0];
            // 如果acc中还没有这个日期，则创建一个新的数组
            if (!acc[dateKey]) {
                acc[dateKey] = [];
            }
            // 将当前对象添加到对应日期的数组中
            acc[dateKey].push(currentObj);
            // 返回累加器（即修改后的acc对象）
            return acc;
        }, {});
    }


    const dialogHtml = (item) => {
        return <>
            {
                item.role === 0 ? <div key={item.date + currentChat.id + 'all'} className="group flex gap-3 w-full flex-row-reverse mt-2">
                    <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                        <div className="px-4 py-2 w-full ask">
                            <div className="markdown-body markdown-custom-styles !text-base font-normal">
                                <p>{item.msg}</p>
                            </div>
                        </div>
                    </div>
                    {copyHtml(item.msg)}
                </div>
                    : <>{
                        item.role === 1 ? <div key={item.date + currentChat.id + 'all'} className="group flex gap-3 w-full flex-row mt-2">
                            <div className="flex flex-col w-11/12  max-w-fit items-start gap-2">
                                <div className="px-4 py-2 w-full answer">
                                    <div className="markdown-body markdown-custom-styles !text-base font-normal" dangerouslySetInnerHTML={{ __html: marked(item.msg) }}>
                                    </div>
                                </div>
                            </div>
                            {copyHtml(item.msg)}
                        </div> : <>{loading(item)}</>
                    }</>
            }
        </>
    }

    return (
        <>
            <div className="main">
                <div className="px-[15px] py-3 h-full overflow-hidden" style={{paddingLeft:'0'}}>
                    <div className="flex flex-col overflow-hidden h-full">
                        <div className={"grid overflow-hidden grow auto-rows-fr gap-3 mb-3 grid-cols-" + (layerMap[layerCount])}>
                            {
                                list && list.map((currentChat) => {
                                    return (
                                        <div key={currentChat.id} className="flex flex-col overflow-hidden bg-primary-background h-full rounded-[10px]">
                                            <div className="border-b border-solid border-primary-border flex flex-row items-center justify-between gap-2 py-[10px] mx-5">
                                                <div className="flex flex-row items-center gap-2">
                                                    <img alt='' src={currentChat.icon} className="w-[18px] h-[18px] object-contain rounded-full" />
                                                    <span className="font-semibold text-primary-text text-sm cursor-default" data-state="closed">{currentChat.name}</span>
                                                </div>
                                                <div className="flex flex-row items-center gap-3">
                                                    <img src={HistorySvg} alt='' onClick={() => { checkHistory(currentChat) }} className="w-5 h-5 cursor-pointer" data-state="closed" />
                                                    {/* <img src={ShareSvg} alt='' className="w-5 h-5 cursor-pointer" data-state="closed" /> */}
                                                    <img src={ClearSvg} alt='' onClick={() => { setVisibleTips(true);setCurrentChat(currentChat) }} className="w-5 h-5 cursor-pointer" data-state="closed" />
                                                </div>
                                            </div>
                                            <div id={'scrollDiv'+currentChat.id} style={{paddingBottom:'20px'}} className="react-scroll-to-bottom--css-dhbsr-79elbk overflow-auto h-full">
                                                <div className="react-scroll-to-bottom--css-dhbsr-1n7m0yu">
                                                    <div className="flex flex-col gap-3 h-full mx-5">
                                                        {/* 对话 */}
                                                        {
                                                            dialog[currentChat.id] && dialog[currentChat.id]?.log && dialog[currentChat.id]?.log.map((item) => {
                                                                return dialogHtml(item)
                                                            })
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                            <div style={{display:'none'}} className="mt-3 flex flex-col mx-5 mb-[5px]">
                                                <div className="flex flex-row items-center gap-[5px] mb-0"><span
                                                    className="font-medium text-xs text-light-text">Send to ChatGPT</span>
                                                    <hr className="grow border-primary-border" />
                                                </div>
                                                <form className="flex flex-row items-center gap-3">
                                                    <div className="w-full flex flex-col justify-center"><textarea
                                                            className="resize-none overflow-x-hidden overflow-y-auto  w-full outline-none text-sm text-primary-text bg-transparent scrollbar-thin"
                                                            autoComplete="off" name="input" placeholder="" style={{ height: "20px" }}></textarea></div>
                                                    <button type="button" className="rounded-full text-sm px-4 py-1 text-primary-text bg-secondary invisible">
                                                        <div className="flex flex-row items-center gap-1 min-w-max"><span>-</span></div>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    )
                                })
                            }
                        </div>
                        <div className="flex flex-row gap-3">
                            <div className="flex flex-row items-center gap-3 rounded-[15px] bg-primary-background px-4 py-2 grow">
                                <div className="w-full flex flex-col justify-center" aria-expanded="false" aria-haspopup="listbox">
                                <textarea
                                    disabled={!sendState}
                                    id="myTextarea"
                                    onKeyDown={bindEnter}
                                    className="resize-none overflow-x-hidden overflow-y-auto  w-full outline-none text-sm text-primary-text bg-transparent scrollbar-thin"
                                    autoComplete="off" name="input" placeholder="Shift+Enter添加换行"
                                    style={{ height: "40px" }}></textarea>
                                </div>
                                <div className="flex flex-row items-center gap-[10px] shrink-0">
                                    {
                                        sendState ? <button onClick={() => {
                                            sendMsg()
                                        }} type="submit" className="rounded-full text-base font-medium px-6 py-[5px] text-white">
                                            <div className="send_btn">发送</div>
                                        </button>
                                            :
                                            <button onClick={() => {
                                                cancelSend()
                                            }} type="submit" className="rounded-full text-base font-medium px-6 py-[5px] text-primary-text">
                                                <div className="cancel_btn">停止</div>
                                            </button>
                                    }
                                </div>
                            </div>
                        </div>
                        <div className='kong'></div>
                    </div>
                </div>
            </div>

            <Modal
                className={'history_modal'}
                title={<p>与<span style={{ fontWeight: 'bold' }}>{currentChat?.name}</span>的聊天记录</p>}
                visible={visibleHisory}
                footer={null}
                onCancel={() => {
                    setVisibleHisory(false);
                }}
                style={{ width: '1000px', height: '600px', background: '#F8F8F8', borderRadius: '20px' }}
            >
                <div className="react-scroll-to-bottom--css-vwhnp-1n7m0yu history_content">
                    <div className='rounded-[10px] w-full flex flex-row text-primary-text search_history'>
                        <div className='icon_search_box'>
                            <IconSearch className='icon_search' />
                        </div>
                        <Input className='search_input' onPressEnter={(e) => {
                            console.log(e.target.value)
                        }} style={{ width: '100%' }} allowClear placeholder='请输入聊天内容进行搜索' />
                    </div>
                    <div className="flex flex-col gap-3 h-full history_content_scroll">
                        {
                            Object.keys(historyGroup).map((key) => {
                                return <div className='history_item'>
                                    <p className='date_history'>{key}</p>
                                    {
                                        historyGroup[key].map((item) => {
                                            return dialogHtml(item)
                                        })
                                    }
                                </div>
                            })
                        }
                    </div>
                </div>
            </Modal>

            <Modal
                className="xzy_modal"
                style={{
                    width: '260px',
                    height: '176px',
                    border: '1px solid #D6D6D6',
                    borderRadius: '20px'
                }}
                title='温馨提示'
                visible={visibleTips}
                autoFocus={true}
                onCancel={() => setVisibleTips(false)}
                footer={<div className='btns'>
                    <div className='butn cancel' onClick={() => setVisibleTips(false)}>取消</div>
                    <div className='butn confirm' onClick={() => {
                        setVisibleTips(false)
                        clearHistory()
                    }}>确定</div>
                </div>}
            >
                <div className='tipscontent'>
                    是否确定删除聊天记录
                </div>
            </Modal>
        </>
    );
}

export default All;
